import { setToken, getToken, removeToken, removeUserInfo, setUserInfo, setMqttInfo } from '@/utils/auth'
import { userlogin, userlogout } from "@/api/dataReq.js"
import { resetRouter } from '@/router'
import { Message } from 'element-ui'
import { mqttConnection, sendMqttMsg } from '@/utils/mqttClient'
import {setDataAes, getDataAes} from '@/webencrypt/index'

const defaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: ''
  }
}

const state = defaultState()
   
   const mutations = {
    SET_TOKEN: (state, token) => {
      state.token = token 
    },
    RESET_STATE: (state) => {
      Object.assign(state, defaultState())
    },


    // setToken(state, token) {
    //     // 存入vuex
    //     state.token = token
    //     // 存入本地
    //     setToken(token)
    //   },
    //   setUserInfo(state, userInfo) {
    //     state.userInfo = userInfo
    //   },
    //   // 清除用户数据的方法
    //   removeUserInfo(state) {
    //     state.token = ''
    //     state.userInfo = {}
    //     removeToken()
    //     // 重置路由
    //     // resetRouter()
    //   }

   }
   
   const actions = {
    Login({ commit }, reqData) {
      // const { username, password } = userInfo
      return new Promise((resolve, reject) => {
        userlogin(reqData).then(response => {
          if (response.code == '1') {
            commit('SET_TOKEN', response.token)
            
						setToken(response.token)
						setUserInfo(response.data[0])
            resolve()
            // console.log(response)
            // 登录成功就去连接mqtt

            var secret = cfg.secret
            var mqtt_data = JSON.parse(getDataAes(secret, response.mqtt))
            setMqttInfo(mqtt_data)
            mqttConnection(mqtt_data)

            Message({
            message: '登录成功',
            type: 'success',
            
             })
          } else {
            Message({
              message: '登录失败',
              type: 'error',
              
               })
            
          }
        }).catch(error => {
          console.log('err', error)
          reject(error)
        })
      })
    },

    Logout({ commit, state }) {
      return new Promise((resolve, reject) => {
        userlogout().then(() => {
          removeToken() // must remove  token  first
          removeUserInfo()
          resetRouter()
          commit('RESET_STATE')
          resolve()
          Message({
            message: '退出成功',
            type: 'success',
            
             })
        }).catch(error => {
          reject(error)
        })
      })
    },

    resetToken({ commit }) {
      return new Promise(resolve => {
        removeToken() // must remove  token  first
        commit('RESET_STATE')
        resolve()
      })
    },


  }

  
   
   
   export default {
     namespaced: true,     // 有效防止命名冲突,与其他modules组件命名, 类似于样式加scoped,组件样式命名冲突  
     state,
     mutations,
     actions
   }
   